// app/middleware/error_handler.go
package middleware

import (
	"gin-zc/util"
	"net/http"

	"github.com/gin-gonic/gin"
)

type ErrorResponse struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Details any    `json:"details,omitempty"`
}

func ErrorHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()

		// 检查是否有错误
		if len(c.Errors) > 0 {
			err := c.Errors.Last()
			handleError(c, err.Err)
		}
	}
}

func handleError(c *gin.Context, err error) {
	var statusCode int
	var message string

	switch e := err.(type) {
	case *util.BusinessError:
		statusCode = e.StatusCode
		message = e.Message
	default:
		statusCode = http.StatusInternalServerError
		message = "Internal Server Error"
	}

	c.JSON(statusCode, ErrorResponse{
		Code:    statusCode,
		Message: message,
	})
}
